package wibrst.visual {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.getTimer;
	import wibrst.utils.ColorUtil;
	
	/**
	 * ...
	 * @author wibrst@qq.com
	 */
	public class VPerfermanceMoniter extends Sprite{
		
		public function VPerfermanceMoniter( iSample:int = 30, bAutoStart:Boolean = true ) {
			this._iSample = iSample;
			this._vRectBack = new VRect( 100, 20, 0x66C322 );
			this.addChild( this._vRectBack );
			
			this.addEventListener(Event.ENTER_FRAME, engineHandler);
			this.reset();
			
			if (bAutoStart) {
				this.startFPSMonitoring();
			}
		}
		
		private function reset():void{
			this._bFPSMonitoring = false;
		}
		
		public function startFPSMonitoring():void {
			this._bFPSMonitoring = true;
			this._vcTimePoint = new Vector.<Number>;
		}
		
		private function engineHandler(e:Event):void {
			if ( this._bFPSMonitoring ) {
				this._vcTimePoint.push( getTimer() );
				if ( this._vcTimePoint.length > this._iSample ) {
					this._vcTimePoint.shift();
					var sRes:String = Number( 
						( this._vcTimePoint.length - 1 ) * 1000 / ( this._vcTimePoint[ this._vcTimePoint.length - 1] - this._vcTimePoint[0] )
					).toFixed( 2 );
					this.txFPS.text = "FPS:" + sRes;
				}
			}
		}
		
		private var _bFPSMonitoring:Boolean;
		private var _txFPS:TextField;
		private var _vRectBack:VRect;
		
		private var _iSample:int;
		private var _vcTimePoint:Vector.<Number>;
		
		public function get txFPS():TextField { 
			if ( ! _txFPS ) {
				var tf:TextFormat = new TextFormat( 'Tahoma', 10, 0x000000, true );
				this._txFPS = new TextField;
				this._txFPS.defaultTextFormat = tf;
				this._txFPS.selectable = false;
				this._txFPS.x = 5;
				this.addChild( this._txFPS );
			}
			return this._txFPS; 
		}
		
	}

}